package api

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"week_one/client/common/global"
	jwtRequest "week_one/client/vender/jwt"
	user "week_one/user_srv/proto"
)

func Register(ctx *gin.Context) {
	username := ctx.PostForm("username")
	password := ctx.PostForm("password")
	res, err := global.UserClient.Register(ctx, &user.RegisterReq{
		Username: username,
		Password: password,
	})
	if err != nil {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"code": http.StatusUnauthorized,
			"msg":  err.Error(),
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "register success",
		"data": res.Userid,
	})
}
func UserLogin(ctx *gin.Context) {
	username := ctx.PostForm("username")
	password := ctx.PostForm("password")
	res, err := global.UserClient.UserLogin(ctx, &user.UserLoginReq{
		Username: username,
		Password: password,
	})
	if err != nil {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"code": http.StatusUnauthorized,
			"msg":  err.Error(),
		})
		return
	}
	//token
	token, err := jwtRequest.AuthToken(uint(res.Id), res.Username)
	if err != nil {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"code": http.StatusUnauthorized,
			"msg":  err.Error(),
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "register success",
		"data": token,
	})
}
